import React, { Component } from "react";
import { Checkbox, Select, Spin } from "antd";
import MultiSelectorV2 from "components/template/multi-selector";
import { deepCopy, messages } from "share/common";
import CompactInput from "components/compact-input";
import "styles/setting/development-platform/dingtalk-comp.scss";

const map = [
  {
    key: "ON_BUSINESS",
    text: messages("basic-12.key22") /*出差申请*/,
    tips: messages("basic-12.key23") /*启用后，所选申请单审批通过后将在钉钉考勤数据中同步为“出差”。*/,
  },
  {
    key: "WORK_OVERTIME",
    text: messages("basic-12.key24") /*加班申请*/,
    tips: messages("basic-12.key25") /*启用后，所选申请单审批通过后将在钉钉考勤数据中同步为“加班”。*/,
  },
  {
    key: "GO_OUT",
    text: messages("basic-12.key26") /*外出申请*/,
    tips: messages("basic-12.key27") /*启用后，所选申请单审批通过后将在钉钉考勤数据中同步为“外出”。*/,
  },
  {
    key: "ASK_FOR_LEAVE",
    text: messages("basic-12.key28") /*请假申请*/,
    tips: messages("basic-12.key29") /*启用后，所选申请单审批通过后将在钉钉考勤数据中同步为“请假”。*/,
  },
];

class DingTalkComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectValue: "part",
      check: {
        ON_BUSINESS: false,
        GO_OUT: false,
        ASK_FOR_LEAVE: false,
        WORK_OVERTIME: false,
      },
      selectorItem: {
        service: this.handleService,
        key: "formOID",
        labelKey: "formName",
        label: "formName",
        descriptionKey: this.handleDesc,
        enableKey: "valid",
      },
      forms: this.props.forms,
      selectOIDs: [],
      result: {},
    };
    this.tempResult = {};
    this.tempCheck = {};
    this.saved = false;
    this.handled = false;
    this.commonObj = {
      ON_BUSINESS: [{ effectiveRange: "all" }],
      GO_OUT: [],
      ASK_FOR_LEAVE: [],
      WORK_OVERTIME_1: [],
      WORK_OVERTIME_2: [],
    };
  }

  handleDesc = (data) => {
    if (data.fromType === 2) {
      return data.setOfBooksName;
    } else if (data.fromType === 1) {
      return data.companyName;
    }
    return null;
  };

  handleService = () => {
    const { forms, result } = this.state;
    const selectOIDs = [];
    Object.keys(result).forEach((key) => {
      result[key].forEach((single) => {
        selectOIDs.push(single.formOid);
      });
    });
    return new Promise((resolve, reject) => {
      resolve({ data: forms.filter((item) => !selectOIDs.includes(item.formOID)).filter((item) => item.formOID) });
    });
  };

  componentWillMount() {}

  componentDidMount() {
    const { onRef, value } = this.props;
    onRef && onRef(this);
    this.setValue(value, this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ forms: nextProps.forms }, () => {
      this.setValue(nextProps.value, nextProps);
    });
  }

  setValue = (value, nextProps) => {
    if (value.dingtalkAttendance) {
      if (value.dingDingAttendanceSetting && Object.keys(value.dingDingAttendanceSetting).length !== 0) {
        if (
          value.dingDingAttendanceSetting.ON_BUSINESS &&
          value.dingDingAttendanceSetting.ON_BUSINESS[0] &&
          value.dingDingAttendanceSetting.ON_BUSINESS[0].effectiveRange === "all"
        ) {
          this.setState(
            {
              selectValue: "all",
              result: deepCopy(this.commonObj),
              check: { ON_BUSINESS: true, GO_OUT: false, ASK_FOR_LEAVE: false, WORK_OVERTIME: false },
            },
            () => {
              this.handled = true;
            }
          );
        } else {
          this.setState({ result: value.dingDingAttendanceSetting }, () => {
            this.handleCheck(value.dingDingAttendanceSetting);
          });
        }
      } else {
        this.setState(
          {
            selectValue: "all",
            result: deepCopy(this.commonObj),
            check: { ON_BUSINESS: true, GO_OUT: false, ASK_FOR_LEAVE: false, WORK_OVERTIME: false },
          },
          () => {
            this.handled = true;
            this.dispatchChange();
          }
        );
      }
    } else {
      const result = deepCopy(this.commonObj);
      result.ON_BUSINESS = [];
      this.setState({
        check: { ON_BUSINESS: false, GO_OUT: false, ASK_FOR_LEAVE: false, WORK_OVERTIME: false },
        result,
      });
      if (!nextProps.loading) {
        this.handled = true;
      }
    }
  };

  handleCheck = (results) => {
    if (this.handled) return;
    const { check } = this.state;
    Object.keys(check).forEach((key) => {
      check[key] = false;
    });
    Object.keys(results).forEach((key) => {
      if (results[key].length !== 0) check[key] = true;
      else check[key] = false;
    });
    if (check.WORK_OVERTIME_1 || check.WORK_OVERTIME_2) check.WORK_OVERTIME = true;
    delete check.WORK_OVERTIME_1;
    delete check.WORK_OVERTIME_2;
    this.setState({ check }, () => {
      this.handled = true;
    });
  };

  dispatchChange = () => {
    const { result, check } = this.state;
    const { onChange } = this.props;
    const switchKey = !!Object.keys(check)
      .map((key) => check[key])
      .filter((item) => item).length;
    onChange && onChange({ dingtalkAttendance: switchKey, dingDingAttendanceSetting: result });
  };

  reset = () => {
    this.tempResult = {};
    this.tempCheck = {};
    this.saved = false;
  };

  onChange = (e, key) => {
    this.reset();
    const { result, check, selectValue } = this.state;
    if (!e.target.checked) {
      if (key === "WORK_OVERTIME") {
        result.WORK_OVERTIME_1 = [];
        result.WORK_OVERTIME_2 = [];
      } else {
        result[key] = [];
      }
    }
    if (!e.target.checked && selectValue === "all" && key === "ON_BUSINESS") this.setState({ selectValue: "part" });
    check[key] = e.target.checked;
    this.setState({ result, check }, this.dispatchChange);
  };

  formsChange = (data, key) => {
    this.reset();
    const { result } = this.state;
    result[key] = data.map((item) => {
      return {
        formOid: item.formOID || item.formOid,
        formOID: item.formOID || item.formOid,
        formName: item.formName,
        effectiveRange: "part",
      };
    });
    this.setState({ result }, this.dispatchChange);
  };

  selectChange = (e) => {
    const { result, check } = this.state;
    if (e === "all") {
      //做临时保存
      this.tempResult = result;
      this.tempCheck = check;
      this.saved = true;
      this.setState(
        {
          selectValue: e,
          check: { ON_BUSINESS: true, GO_OUT: false, ASK_FOR_LEAVE: false, WORK_OVERTIME: false },
          result: deepCopy(this.commonObj),
        },
        this.dispatchChange
      );
      return;
    } else if (this.saved) {
      this.setState(
        {
          selectValue: e,
          check: this.tempCheck,
          result: this.tempResult,
        },
        this.dispatchChange
      );
      return;
    }
    result.ON_BUSINESS = [];

    this.setState({ selectValue: e, result }, this.dispatchChange);
  };

  renderCheckBox = () => {
    const { selectValue, selectorItem, result } = this.state;

    return map.map((item) => {
      return (
        <div className={this.state.check[item.key] ? "" : "margin-bottom"}>
          <div>
            <Checkbox
              checked={this.state.check[item.key]}
              disabled={item.key !== "ON_BUSINESS" ? selectValue === "all" && this.state.check.ON_BUSINESS : false}
              onChange={(e) => {
                this.onChange(e, item.key);
              }}
              style={{ userSelect: "none" }}
            >
              {item.text}
            </Checkbox>
          </div>
          <div className="check-tips">{item.tips}</div>
          {this.state.check[item.key] && (
            <div className={`select-area ${item.key === "ON_BUSINESS" ? "width-93" : ""}`}>
              {item.key === "ON_BUSINESS" ? (
                <CompactInput className={"ding-talk-compact"}>
                  <Select
                    value={selectValue}
                    onChange={this.selectChange}
                    placeholder={messages("common.select") /*请选择*/}
                  >
                    <Select.Option key={"all"}>{messages("common.all") /*全部*/}</Select.Option>
                    <Select.Option key={"part"}>{messages("request-2.key10") /*部分*/}</Select.Option>
                  </Select>
                  <MultiSelectorV2
                    disabled={selectValue === "all"}
                    isAll={selectValue === "all"}
                    type="expense_label"
                    isShowSelectAll
                    selectorItem={selectorItem}
                    onChange={(data) => {
                      this.formsChange(data, item.key);
                    }}
                    value={result[item.key]}
                  />
                </CompactInput>
              ) : item.key === "WORK_OVERTIME" ? (
                <div>
                  <div className={"other-title"}>{messages("basic-12.key30") /*加班转调休*/}</div>
                  <MultiSelectorV2
                    type="expense_label"
                    isShowSelectAll
                    selectorItem={selectorItem}
                    onChange={(data) => {
                      this.formsChange(data, `${item.key}_1`);
                    }}
                    value={result[`${item.key}_1`]}
                  />
                  {/*<div style={{ marginTop: 12 }} className={"other-title"}>*/}
                  {/*  {messages("basic-12.key31") /*加班转工资*!/*/}
                  {/*</div>*/}
                  {/*<MultiSelectorV2*/}
                  {/*  type="expense_label"*/}
                  {/*  isShowSelectAll*/}
                  {/*  selectorItem={selectorItem}*/}
                  {/*  onChange={(data) => {*/}
                  {/*    this.formsChange(data, `${item.key}_2`);*/}
                  {/*  }}*/}
                  {/*  value={result[`${item.key}_2`]}*/}
                  {/*/>*/}
                </div>
              ) : (
                <MultiSelectorV2
                  type="expense_label"
                  isShowSelectAll
                  selectorItem={selectorItem}
                  onChange={(data) => {
                    this.formsChange(data, item.key);
                  }}
                  value={result[item.key]}
                />
              )}
            </div>
          )}
        </div>
      );
    });
  };

  render() {
    const { loading } = this.props;
    return (
      <div className={"ding-talk-comp"}>
        <div className="tips-group">
          <div>{messages("basic-12.key32") /*以下对接类型均满足下列条件：*/}</div>
          <div>
            {messages("basic-12.key33") /*1，每种申请单最多只能对接一种考勤类型，下拉选项都是未对接考勤的差旅申请单；*/}
          </div>
          <div>
            {
              messages(
                "basic-12.key34"
              ) /*2，申请单开始时间不能早于当前时间前31天，否则无法同步考勤数据到超出范围的日期中；*/
            }
          </div>
          <div>
            {
              messages(
                "basic-12.key35"
              ) /*3，计算方式按工作日计算，即不包含员工的休息日，例如未排班的双休日、法定节假日。*/
            }
          </div>
        </div>
        <Spin spinning={loading}>{this.renderCheckBox()}</Spin>
      </div>
    );
  }
}

DingTalkComp.propTypes = {};

export default DingTalkComp;
